$(function() {
	console.log(66)
	console.log()
	var car_type={};
	var from_lonlat=[];
	var company={};
	Load()
	$.ajax({
		url: '{:url("adminapi/Order/orderList")}',
		data: {
			where_json:JSON.stringify({
				order_id:['in','{:input("param.order_id")}']
			})
		},
		type: 'post',
		success: function(res) {
			Load(1)
			res=orderstate(res)
			console.log(res)
			for(var key in res.data[0]){
				if(res.data[0].booking_type==2){
					$('.pre_meter_w').css('display','none')
				}
				if(key=='pre_meter'){
					$('.'+key).html(res.data[0][key]/1000)
				}else{
					$('.'+key).html(res.data[0][key])
				}
				
			}
			from_lonlat=[res.data[0].from_lon, res.data[0].from_lat];
			car_type.name=res.data[0].car_type_name;
			car_type.id=res.data[0].car_type_id;
			company.name=res.data[0].company_name;
			company.id=res.data[0].company_id;
			console.log(res.data[0].order_state)
			if(res.data[0].order_state==2||res.data[0].order_state==4){
				$('.dispatch-btn1').css('display','inline-block')
				$('.dispatch-btn2').css('display','none')
			}else if(res.data[0].order_state>=5&&res.data[0].order_state<8){
				$('.dispatch-btn1').css('display','none')
				$('.dispatch-btn2').css('display','inline-block')
				$('.driver_id').val(res.data[0].driver_id)
				$('.driver').val(res.data[0].driver_name)
				$('.CarId').val(res.data[0].car_id)
				$('.car_number').val(res.data[0].car_number)
                $('.redispatch').val(1);
			}
			$('.show_map').on('click',function(){
				AMapUI.loadUI(['overlay/SimpleMarker'], function(SimpleMarker) {
				layer.open({
					type: 1,
					skin: 'layui-layer-rim', //加上边框
					title:false,
					area: ['500px', '500px'], //宽高
					content: `<div id='map' style='height:100%'></div>`,
					success:function(){
						console.log(res)
						var qd=[118.57, 24.82];
						if(res.data[0].from_lon){
							qd=[res.data[0].from_lon, res.data[0].from_lat]
						}
						map = new AMap.Map('map', {
							resizeEnable: true,
							zoom: 10,
							center: qd
						});
						var iconStyles = SimpleMarker.getBuiltInIconStyles('fresh');
						
						if(res.data[0].from_lon){
							console.log(res.data[0].from_lon+','+res.data[0].from_lat)
						var from_latlng=new SimpleMarker({ 
							//普通文本
							iconStyle: iconStyles[2],
							//图标文字
							iconLabel: {
								//A,B,C.....
								innerHTML: '起',
								style: {
									color: '#fff'
								}
							}, 
							map: map,
							position: [res.data[0].from_lon, res.data[0].from_lat],
							
						});
						}
						if(res.data[0].to_lon){
							console.log(res.data[0].to_lon+','+res.data[0].to_lat)
					    var to_latlng=new SimpleMarker({ 
							//普通文本
							iconStyle: iconStyles[2],
							//图标文字
							iconLabel: {
								//A,B,C.....
								innerHTML: '终',
								style: {
									color: '#fff'
								}
							}, 
							map: map,
							position: [res.data[0].to_lon, res.data[0].to_lat],
							
						});
					  }
					}
				});
				});
			})
		}
	})
	
	layui.use(['layer', 'laydate', 'form','table', 'element', 'laytpl'], function() {
		var layer = layui.layer,
			laydate = layui.laydate,
			element = layui.element,
			laypage = layui.laypage,
			table = layui.table,
			form = layui.form,
			laytpl = layui.laytpl;
			
			//显示地图
			
		$('.dispatch-btn1').on('click',function(){
			sendForm($(this));
		});
		$('.dispatch-btn2').on('click',function(){
			sendForm($(this));
		});	
			
//		paidan()
		$('.driver').on('click',function(){
			var data1={};
			
			paidan(data1,car_type,company)
		})
		$('.car_number').on('click',function(){
			var data1={};
			paidan(data1,car_type,company)
		})
		function paidan(data,car_type,company) {
			if(data){}else{
				data={}
			}
			var where_json = {};
			var paidan = layer.open({
				type: 1,
				offset: 'auto',
				title: '派车选择',
				shade: 0,
				skin: 'layui-layer-rim', //加上边框
				area: ['80%', '80%'], //宽高
				content: `<div style='padding:10px;font-size:14px'>
		  	<div class='margin_bottom_10 am-u-sm-12 cl-p'>
			  	<form class='layui-form'>
		  			<div class="layui-form-item">
			  			<div class="layui-input-inline">
							<input type="text" name="company_name"  placeholder="请选择公司" class="layui-input company_name" >
							<input type="hidden" name="company_id"  placeholder="请选择公司" class="layui-input company_id" >
							<span class="input-group-addon close-input"><i class="am-icon-close"></i></span> 
						</div>
			  			<div class="layui-input-inline">
							<input type="text" name="car_type_name" value='${car_type.name}' placeholder="请选择车型" class="layui-input car_type" >
							<input type="hidden" name="car_type_id"  value='${car_type.id}' placeholder="请选择公司" class="layui-input car_type_id" >
							<span class="input-group-addon close-input"><i class="am-icon-close"></i></span> 
						</div>
						<div class="layui-input-inline">
							<input type="text" name="number" placeholder="请输入车牌号" class="layui-input number" >
						</div>
						<div class="layui-input-inline">
							<select name="work_state">
								<option  value="">所有状态</option>
								<option  value="1">执行任务中</option>
								<option  value="2">有预约订单</option>
								<option selected value="3">听单中</option>
								<option  value="4">下班</option>
							</select>
						</div>
						<div>
							<button type='button' class="layui-btn layui-btn layui-btn-normal" lay-submit lay-filter="search_driver">查询</button>
						</div>
			  		</div>
			  		<div class="layui-form-item">
			  			<div class="layui-input-inline">
							<input type="text" name="phone" placeholder="请输入手机号" class="layui-input phone" >
						</div>
						<div class="layui-input-inline">
							<input type="text" name="driver_name" placeholder="请输入司机姓名" class="layui-input driver_name" value="{$Think.get.car_type_name}">
						</div>
					</div>
		  		<form>
		  	</div>
		  	
		  	<div class="am-u-sm-12 cl-p" style='font-size:12px'>
				
			</div>	
		  	<table  class="layui-hide" id='driver_dispatch' lay-filter="driver_dispatch"></table>
		  	<div id='page'></div>
		  	<div class="am-u-lg-12 am-cf" style='color:#888'>
				
				<div class="am-fr">
					<ul class="pagination">
						
					</ul>
				</div>
			</div>
			<div class="am-u-lg-12 am-cf">
					
				
			</div>
		  </div>`,
				success: function() {
					form.render('select')
					$('.close-input').unbind();
					$('.close-input').on('click',function(){
				console.log(1)
				for(var i=0;i<$(this).parent().find('input').length;i++){
					$(this).parent().find('input').eq(i).val('')
				}
				
			});
					var fi = 1;
					var main = [
						[ //表头
							{
								title: '是否选中',
								toolbar: '#choose',
								fixed: 'left'
							}, {
								field: 'name',
								title: '司机姓名'
							}, {
								field: 'company_name',
								width: 250,
								title: '单位',
								sort: true
							}, {
								field: 'phone',
								title: '电话'
							}, {
								field: 'cartype_and_number',
								width: 250,
								title: '车型/车牌号',
								toolbar: '#relevance',
							}, {
								field: 'work_state2',
								title: '状态',
								sort: true
							}, {
								field: 'update_time',
								title: '位置更新时间',
								sort: true
							}, {
								field: 'to_form_addr',
								title: '距离出发地'
							}
						]
					];
					let data = {
						page: 1,
						pagenum: 10
					}
					let where_json={};
					// 暂且不选择该订单中的单位
					// where_json.company_id=['in',company.id];
					where_json.work_state=3;
					where_json.car_type_id=['in',car_type.id];
					data.where_json=JSON.stringify(where_json)
					ajaxdriver_dis(data)
					$('.company_name').on('click',function(){
						choosecar('{:url("admin/company/index")}?op=search')
					});
					$('.car_type').on('click',function(){
						choosecar('{:url("admin/models/index")}?op=search')
					});
					function ajaxdriver_dis(data) {
						
						console.log(data)
						Load()
						$.ajax({
							url: '{:url("open/Plus/getDriver")}',
							data: data,
							type: 'post',
							success: function(res) {
								console.log(res)
								if(res.data){}else{
									res.data=[];
								}
								Load(1)
								for(var i = 0; i < res.data.length; i++) {
//									
//									

									//*****计算距离出发地距离********/
									
									var p1 = from_lonlat;
									var p2 = [res.data[i].lon, res.data[i].lat];
									if(res.data[i].lon&&from_lonlat[0]){
										var dis = AMap.GeometryUtil.distance(p1, p2);
										res.data[i].to_form_addr = (dis/1000).toFixed(2)+'公里';
										res.data[i].origin_distance = dis;
									}
									
									res.data[i].company_name=res.data[i].company.company_name
									res.data[i].company_id=res.data[i].company.company_id
									res.data[i].car_type_id=res.data[i].car.car_type_id
									res.data[i].car_type_name=car_type.name
									
									res.data[i].car_id=res.data[i].car.car_id
									res.data[i].number=res.data[i].car.number

									res.data[i].company_name=res.data[i].company.company_name
									if(res.data[i].work_state == 1) {
										res.data[i].work_state2 = '执行任务中';
									} else if(res.data[i].work_state == 2) {
										res.data[i].work_state2 = '有预约单';
									} else if(res.data[i].work_state == 3) {
										res.data[i].work_state2 = '听单中';
									} else if(res.data[i].work_state == 4) {
										res.data[i].work_state2 = '下班';
									}
									res.data[i].cartype_and_number = (res.data[i].car_type_name ? res.data[i].car_type_name : '未获取车型') + '/' + (res.data[i].number ? res.data[i].number : '无绑定车辆');
								}

                                res.data.sort(function(a, b){
                                	return a.origin_distance - b.origin_distance
								})

								table.render({
									elem: '#driver_dispatch',
									cols: main,
									limit: data.pagenum,
									data: res.data
								});
								if(fi == 1) {
									console.log(res.count)
									laypage.render({
										elem: 'page',
										count: res.count,
										layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
										theme: '#1E9FFF',
										jump: function(obj, first) {
											if(!first) {
												page = obj.curr
												data.page = page
												pagenum = obj.limit
												data.pagenum = pagenum
												ajaxdriver_dis(data)
											} else {

											}
										}
									});
									fi = 2
								}
								
								form.on('submit(search_driver)', function(data){
									fi=1
								  console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
								  let where_json={}
								  if(data.field.company_id){where_json.company_id=['in',data.field.company_id];}
								  if(data.field.car_type_id){where_json.car_type_id=['in',data.field.car_type_id];}
								  if(data.field.number){ where_json.number=['like','%'+data.field.number+'%'];}
								  if(data.field.work_state){where_json.work_state=['in',data.field.work_state];}
								  if(data.field.phone){ where_json.phone=['like','%'+data.field.phone+'%'];}
								  if(data.field.driver_name){ where_json.name=['like','%'+data.field.driver_name+'%'];}
								  
//								  where_json.car_type_id=['in',data.field.car_type_id];
//								  where_json.number=['like','%'+data.field.number+'%'];
//								  where_json.work_state=['in',data.field.work_state];
//								  where_json.phone=['like','%'+data.field.phone+'%'];
//								  where_json.driver_name=['like','%'+data.field.driver_name+'%'];
								  console.log(where_json)
								  let data_search={};
								  data_search.where_json=JSON.stringify(where_json)
								  ajaxdriver_dis(data_search)
								  return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
								});
								table.on('tool(driver_dispatch)', function(obj) {
									var data = obj.data; //获得当前行数据
									var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
									var tr = obj.tr; //获得当前行 tr 的DOM对象
									if(obj.event === 'choose') {
										
										data.number = res.data[tr.data('index')].number;
										data.car_id = res.data[tr.data('index')].car_id;
										if(res.data[tr.data('index')].car_id){
											$('.driver').val(data.name);
											$('.driver_id').val(data.driver_id);
											$('.car_number').val(data.number);
											$('.CarId').val(data.car_id);
											layer.close(paidan)
										}else{
											Err('该司机无该车型的绑定车辆，请进行绑定')
										}
										
									} else if(obj.event === 'car_change') { //切换该司机选中的车辆
                                    //***********弹出司机的绑定车辆***********//  
										//弹出改司机的所有绑定的车辆
										var driver_re = layer.open({
											type: 1,
											title: false,
											skin: 'layui-layer-rim', //加上边框
											area: ['420px', '240px'], //宽高
											content: `<div>
							  				<table class='layui-hide' id='driver_re' lay-filter="driver_re"></table>
							  			</div>`,
											success: function() {
												var re_main = [
													[ //表头
														{
															title: '是否选中',
															toolbar: '#choose',
															fixed: 'left'
														}, {
															field: 'number',
															title: '车牌号'
														}, {
															field: 'car_type_name',
															title: '车型',
															sort: true
														}

													]
												];
												Load()
												$.ajax({
													url: '{:url("adminapi/driver/getUseCar")}',
													data: {
														driver_id: data.driver_id
													},
													type: 'post',
													success: function(res1) {
														Load(1)
														console.log(res1)
														var driver_car = [];
														table.render({
															elem: '#driver_re',
															cols: re_main,
															limit: data.pagenum,
															data:res1.data
														});
														table.on('tool(driver_re)', function(re_obj) {
															var re_data = re_obj.data; //获得当前行数据
															var re_layEvent = re_obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
															var re_tr = re_obj.tr; //获得当前行 tr 的DOM对象
															if(re_obj.event === 'choose') {
															 tr.find('td').each(function(){
														      	if($(this).data('field')=='cartype_and_number'){
														      		var cartype_and_number_name=re_data.car_type_name+'/'+re_data.number
														      		$(this).find('.cartype_and_number').html(cartype_and_number_name)
														      		res.data[tr.data('index')].car_type_name=re_data.car_type_name;
														      		res.data[tr.data('index')].car_type_id=re_data.car_type_id;
														      		res.data[tr.data('index')].number=re_data.number;
														      		res.data[tr.data('index')].car_id=re_data.car_id;
														      	}
														      })
															 layer.close(driver_re)
															}
														})
													}
												})
											}
										});
				     
									//***********弹出司机的绑定车辆-结束***********//  
									}
								});
							}
						})
					}
				}
			});
		}
	})
})